<?php
namespace backend\logic;

use think\Db;
use think\db\Where;
use external\SFTools;

class OrderLogic {
    /**
     * 获取订单列表
     * @param   string $order_number 订单号
     * @param   array  $userFind     用户对象
     * @return  array                数组列表数据
     */
    public function getOrderListBuyOrderNumber($order_number, $userFind = array()){
        if (empty($userFind['fccode'])) {
            return SFTools::err("3300", array("fccode" => $userFind['fccode']));
        }
        if (empty($userFind['user_uuid'])) {
            return SFTools::err("3300", array("user_uuid" => $userFind['user_uuid']));
        }
        if (empty($order_number)) {
            return SFTools::err("3300", array("order_number" => $order_number));
        }
        $userAuthLogic = new \backend\logic\UserAuthLogic;
        $userAuthFind = $userAuthLogic->getUserAuthListBuyFccodeAndUserUUID($userFind['fccode'], $userFind['user_uuid']);
        if (empty($userAuthFind)) {
            return SFTools::err("3310");
        }
        if ($userAuthFind['is_private'] == 1) {
            $field = 'fOrdNo,fCCode,fCOrdNo,fOrdRdate,fCryCode,fOrdAllamt,fCFlag,fProNtfFlag,fOutFlag,fIfClose,fIfCancel,fCDate';
        } else {
            $field = 'fOrdNo,fCCode,fCOrdNo,fOrdRdate,fCFlag,fProNtfFlag,fOutFlag,fIfClose,fIfCancel,fCDate';
        }
        $order = new \backend\model_erp\Order;
        
        return $order::field($field)->where('fCCode', $userFind['fccode'])->where('fOrdNo|fCOrdNo', 'like', $order_number . '%')->order('fCDate', 'desc')->limit(10)->select();
    }
    
    /**
     * 获取订单明细
     * @param   string $order_number 订单号
     * @param   array  $userFind     用户对象
     * @return  array                数组对象数据
     */
    public function getOrderFindBuyOrderNumber($order_number, $userFind = array()){
        if (empty($userFind['fccode'])) {
            return SFTools::err("3300", array("fccode" => $userFind['fccode']));
        }
        if (empty($userFind['user_uuid'])) {
            return SFTools::err("3300", array("user_uuid" => $userFind['user_uuid']));
        }
        if (empty($order_number)) {
            return SFTools::err("3300", array("order_number" => $order_number));
        }
        $userAuthLogic = new \backend\logic\UserAuthLogic;
        $userAuthFind = $userAuthLogic->getUserAuthListBuyFccodeAndUserUUID($userFind['fccode'], $userFind['user_uuid']);
        if (empty($userAuthFind)) {
            return SFTools::err("3310");
        }
        if ($userAuthFind['is_private'] == 1) {
            $field = 'fOrdNo,fCCode,fCOrdNo,fOrdRdate,fCryCode,fOrdAllamt,fCFlag,fProNtfFlag,fOutFlag,fIfClose,fIfCancel,fCDate';
            $field2 = 'oi.fOrdNo,oi.fSNo,oi.fGoodsID,oi.fOrdQty,oi.fOCryAmtBfDis,g.fGoodsName,g._x_f022 is_open';
        } else {
            $field = 'fOrdNo,fCCode,fCOrdNo,fOrdRdate,fCFlag,fProNtfFlag,fOutFlag,fIfClose,fIfCancel,fCDate';
            $field2 = 'oi.fOrdNo,oi.fSNo,oi.fGoodsID,oi.fOrdQty,g.fGoodsName,g._x_f022 is_open';
        }
        $order = new \backend\model_erp\Order;
        //$field = 'fOrdNo,fCCode,fCOrdNo,fOrdRdate,fCryCode,fOrdAllamt,fCFlag,fProNtfFlag,fOutFlag,fIfClose,fIfCancel,fCDate';
        $orderFind = $order::field($field)->where('fOrdNo', $order_number)->find();
        //$field2 = 'oi.fOrdNo,oi.fSNo,oi.fGoodsID,oi.fOrdQty,oi.fOCryAmtBfDis,g.fGoodsName,g._x_f022 is_open';
        $orderFind['items'] = Db::table(DB_ERP_TABLE_PREFIX . 't_COPD_OrdItem')->field($field2)->alias('oi')->join(DB_ERP_TABLE_PREFIX . 't_BOMM_GoodsMst g', 'oi.fGoodsID = g.fGoodsID')->where('oi.fOrdNo', $orderFind['fOrdNo'])->order('fSNo', 'asc')->select();
        
        return $orderFind;
    }
    
    /**
     * 获取SPU列表
     * @param   string $spu_name SPU名称
     * @param   array  $userFind 用户对象
     * @param   int    $page     页码
     * @param   int    $size     每页大小
     * @param   string $type     返回类型 type='count' 返回数据总数
     * @return  array                数组对象数据
     */
    public function getSpuListLikeSpuName($spu_name, $userFind = array(), $page, $size, $type){
        if (empty($userFind['fccode'])) {
            return SFTools::err("3300", array("fccode" => $userFind['fccode']));
        }
        if (empty($page)) {
            $page = 1;
        }
        if (empty($size)) {
            $size = 10;
        }
        $fccode = $userFind['fccode'];
        $fRmQltCodeArr = array();
        $where = new Where;
        $custSaleLogic = new \backend\logic\CustSaleLogic;
        $custSaleList = $custSaleLogic->getCustSaleListBuyFccode($fccode);
        foreach ($custSaleList as $key => $value) {
            $fRmQltCodeArr[] = $value['fKey'];
        }
        if (!empty($fRmQltCodeArr)) {
            $where['fRmQltCode'] = array("in", $fRmQltCodeArr);
        }
        if (!empty($spu_name)) {
            $where['spu_name'] = ['like', '%' . $spu_name . '%'];
        }
        $where['fIfUse'] = '1';
        $where['dzIsBuy'] = 'Y';
        if (strtolower($type) == 'count') {
            $field = 'spu_uuid';
            $spuList = Db::table('v_spu_list')->field($field)->where($where)->group('spu_uuid')->count();
        } else {
            $field = 'spu_uuid,spu_name,spu_alias_name,spu_code,fStyleCode,create_datetime,MAX(sku_pic) spu_pic,MAX(sfZDYf1SortName) fSortName1,MAX(fSortName) fSortName2,MAX(fBrandName) fBrandName,MAX(fKitName) fKitName,MAX(fRmQltCode) fRmQltCode';
            $spuList = Db::table('v_spu_list')->field($field)->where($where)->page($page, $size)->group('spu_uuid,spu_name,spu_alias_name,spu_code,fStyleCode,create_datetime')->order('create_datetime DESC')->select();
        }
        
        return $spuList;
    }
    
    /**
     * 获取SPU列表
     * @param   string $spu_uuid SPU 唯一标识
     * @param   string $sku_code 商品二位码
     * @param   string $userFind 登入用户信息，主要使用（$userFind['fccode']）
     * @return  array            数组对象数据
     */
    public function getSkuListBuySpuUUIDorSkuCode($spu_uuid, $sku_code, $userFind = array()){
        if (empty($userFind['fccode'])) {
            return SFTools::err("3300", array("fccode" => $userFind['fccode']));
        }
        $GoodsSku = new \backend\model\GoodsSku;
        if (empty($spu_uuid)) {
            if (empty($sku_code)) {
                return SFTools::err("3300", array("sku_code" => sku_code));
            }
            $field = 'spu_uuid';
            $goodsSkuFind = $GoodsSku::field($field)->where('sku_code', $sku_code)->find();
            if (empty($goodsSkuFind)) {
                return SFTools::err("3309");
            }
            $spu_uuid = $goodsSkuFind['spu_uuid'];
        }
        $fccode = $userFind['fccode'];
        $fRmQltCodeArr = array();
        $where = new Where;
        $custSaleLogic = new \backend\logic\CustSaleLogic;
        $custSaleList = $custSaleLogic->getCustSaleListBuyFccode($fccode);
        foreach ($custSaleList as $key => $value) {
            $fRmQltCodeArr[] = $value['fKey'];
        }
        if (!empty($fRmQltCodeArr)) {
            $where['fRmQltCode'] = array("in", $fRmQltCodeArr);
        }
        $where['spu_uuid'] = $spu_uuid;
        $where['sku_state'] = 1;
        $where['fIfUse'] = '1';
        $where['dzIsBuy'] = 'Y';
        $field = 'sku_uuid,spu_uuid,sku_name,sku_alias_name,attribute_01,attribute_02,sku_pic,fGoodsID,fGoodsCode,fCuM3,dzIsWL,fPackPcs,fPackCtn';
        
        return $GoodsSku::field($field)->where($where)->where('sku_state', 1)->order('attribute_01,attribute_02')->select();
    }
    
    /**
     * 根据客户编码获取草稿单
     * @param   string $userFind 登入用户信息，主要使用（$userFind['fccode']）
     * @return  array            数组对象数据
     */
    public function getDraftOrderBuyFccode($userFind = array()){
        if (empty($userFind['fccode'])) {
            return SFTools::err("3300", array("fccode" => $userFind['fccode']));
        }
        $fccode = $userFind['fccode'];
        $orderFind = $this->getOrderFind($fccode, 0);
        $promotion_uuid = DAILY_PROMOTION_UUID;
        $promotion = new \backend\model\Promotion;
        $promotionFind = $promotion::field('max_volume')->where('promotion_uuid', $promotion_uuid)->find();
        $orderFind['max_volume'] = $promotionFind['max_volume'];
        $orderItem = new \backend\model\OrderItem;
        $orderItemFind = $orderItem::field('SUM(fOrdQty*fCuM3) curr_volume')->where('order_uuid', $orderFind['order_uuid'])->find();
        $orderFind['curr_volume'] = $orderItemFind['curr_volume'];
        
        return $orderFind;
    }

    /**
     * 根据客户编码获取草稿单(PC)
     * @param   string $userFind 登入用户信息，主要使用（$userFind['fccode']）
     * @return  array            数组对象数据
     */
    public function getDraftOrderBuyFccodePC($userFind = array()){
        if (empty($userFind['fccode'])) {
            return SFTools::err("3300", array("fccode" => $userFind['fccode']));
        }
        $fccode = $userFind['fccode'];
        $orderFind = $this->getOrderFind($fccode, 0);
        $promotion_uuid = DAILY_PROMOTION_UUID;
        $promotion = new \backend\model\Promotion;
        $promotionFind = $promotion::field('max_volume')->where('promotion_uuid', $promotion_uuid)->find();
        $orderFind['max_volume'] = $promotionFind['max_volume'];
        $orderItem = new \backend\model\OrderItem;
        $orderItemFind = $orderItem::field('*')->where('order_uuid', $orderFind['order_uuid'])->select();
        $orderFind['items'] = $orderItemFind;

        return $orderFind;
    }
    
    /**
     * 根据款式编码获取定制属性
     * @param   string $fStyleCode 款式编码
     * @return  array            数组对象数据
     */
    public function getCustomBuyFStyleCode($fStyleCode){
        if (empty($fStyleCode)) {
            return array();
        }
        $goodsVirtual = new \backend\model\GoodsVirtual;
        $field = 'fGoodsID,fStyleName,fClrName,fnh,sfZDYf1SortCode SortCode';
        $goodsVirtualList = $goodsVirtual::field($field)->where('fStyleCode', $fStyleCode)->where('fIfUse', '1')->where('dzIsBuy', 'Y')->where('sync_type', 1)->order('fGoodsID')->select();
        if (empty($goodsVirtualList[0])) {
            return array();
        }
        $fGoodsID = $goodsVirtualList[0]['fGoodsID'];
        $SortCode = $goodsVirtualList[0]['SortCode'];
        if($SortCode == 'CD'){
            //床垫类使用长宽定制
            $returnArr['type'] = 1;
            $returnArr['list'] = $goodsVirtualList;
            $virtualList = Db::table('v_virtual_list')->field('fGoodsID,fPropertyCode,fPropertyName,fCode,fDesc,NULL fVal')->where('fGoodsID', $fGoodsID)->order('fGoodsID,fPropertyCode')->select();
        }else{
            //其他类型使用二级定制 $virtualList
            $returnArr['type'] = 2;
            $returnArr['list'][] = $goodsVirtualList[0];
            $virtualList = Db::table('v_virtual_list')->field('fGoodsID,fPropertyCode,fPropertyName,fCode,fDesc,1 isShow')->where('fGoodsID', $fGoodsID)->order('fGoodsID,fPropertyCode')->select();
        }
        $returnArr['virtualList'] = $virtualList;
        
        return $returnArr;
    }
    
    /**
     * 添加常规商品到购物车
     * @param   string $fccode      经销商编码
     * @param   string $order_state 订单状态
     * @return  array               数组对象数据
     */
    public function addSkuToOrder($order_uuid, $goods_id, $fOrdQty, $userFind){
        if (empty($userFind['fccode'])) {
            return SFTools::err("3300", array("fccode" => $userFind['fccode']));
        }
        if (empty($order_uuid)) {
            return SFTools::err("3300", array("order_uuid" => $order_uuid));
        }
        if (empty($goods_id)) {
            return SFTools::err("3300", array("goods_id" => $goods_id));
        }
        if (empty($fOrdQty)) {
            return SFTools::err("3300", array("fOrdQty" => $fOrdQty));
        }
        $fccode = $userFind['fccode'];
        $order = new \backend\model\Order;
        $orderFind = $order::field('order_uuid,promotion_uuid,order_state')->where('fAgencyNo', $fccode)->where('order_uuid', $order_uuid)->find();
        if (empty($orderFind)) {
            return SFTools::err("3801");
        }
        $promotion_uuid = DAILY_PROMOTION_UUID;
        if ($orderFind['promotion_uuid'] != $promotion_uuid) {
            return SFTools::err("3802");
        }
        if ($orderFind['order_state'] != 0) {
            return SFTools::err("3803");
        }
        $goodsSku = new \backend\model\GoodsSku;
        $goodsSkuFind = $goodsSku::field('fGoodsID,fGoodsCode,sku_name fGoodsName,sku_pic,attribute_01 fSizeDesc,attribute_02 fClrName,fCuM3,fPackPcs,fPackCtn,dzIsWL')->where('fGoodsID', $goods_id)->where('sku_state', 1)->where('fIfUse', '1')->where('dzIsBuy', 'Y')->find();
        if (empty($goodsSkuFind)) {
            return SFTools::err("3804");
        }
        $orderItem = new \backend\model\OrderItem;
        $orderItemFind = $orderItem::field('order_item_uuid,fOrdQty,fCuM3')->where('order_uuid', $order_uuid)->where('fGoodsID', $goods_id)->where('fSizeCust', 0)->find();
        if (!empty($orderItemFind)) {
            $fOrdQty = $orderItemFind['fOrdQty'] + $fOrdQty;
        }
        if ($fOrdQty > 9999) {
            return SFTools::err("3805");
        }
        $order_item_uuid = '';
        $fCuM3 = $goodsSkuFind['fCuM3'];
        if (!empty($orderItemFind['order_item_uuid'])) {
            $order_item_uuid = $orderItemFind['order_item_uuid'];
        }
        $bool = $this->check_volume($order_uuid, $order_item_uuid, $fOrdQty, $fCuM3);
        if ($bool) {
            return SFTools::err("3806");
        }
        if (empty($orderItemFind)) {
            $orderItem->order_uuid = $order_uuid;
            $orderItem->fOrdQty = $fOrdQty;
            $orderItem->fGoodsID = $goods_id;
            $orderItem->fGoodsCode = $goodsSkuFind['fGoodsCode'];
            $orderItem->fGoodsName = $goodsSkuFind['fGoodsName'];
            $orderItem->sku_pic = $goodsSkuFind['sku_pic'];
            $orderItem->fClrName = $goodsSkuFind['fClrName'];
            $orderItem->fCuM3 = $goodsSkuFind['fCuM3'];
            $orderItem->fPackPcs = $goodsSkuFind['fPackPcs'];
            $orderItem->fPackCtn = $goodsSkuFind['fPackCtn'];
            $orderItem->dzIsWL = $goodsSkuFind['dzIsWL'];
            $orderItem->save();
        } else {
            $orderItemFind->order_uuid = $order_uuid;
            $orderItemFind->fOrdQty = $fOrdQty;
            $orderItemFind->fGoodsID = $goods_id;
            $orderItemFind->fGoodsCode = $goodsSkuFind['fGoodsCode'];
            $orderItemFind->fGoodsName = $goodsSkuFind['fGoodsName'];
            $orderItemFind->sku_pic = $goodsSkuFind['sku_pic'];
            $orderItemFind->fClrName = $goodsSkuFind['fClrName'];
            $orderItemFind->fCuM3 = $goodsSkuFind['fCuM3'];
            $orderItemFind->fPackPcs = $goodsSkuFind['fPackPcs'];
            $orderItemFind->fPackCtn = $goodsSkuFind['fPackCtn'];
            $orderItemFind->dzIsWL = $goodsSkuFind['dzIsWL'];
            $orderItemFind->save();
        }
        
        return $this->getDraftOrderBuyFccode($userFind);
    }
    
    /**
     * 获取指定经销商和指定状态的订单对象集合
     * @param   string $fccode      经销商编码
     * @param   string $order_state 订单状态
     * @return  array               数组对象数据
     */
    private function getOrderFind($fccode, $order_state){
        $order = new \backend\model\Order;
        $promotion_uuid = DAILY_PROMOTION_UUID;
        $field = 'order_uuid,promotion_uuid,create_datetime';
        $orderFind = $order::field($field)->where('promotion_uuid', $promotion_uuid)->where('fAgencyNo', $fccode)->where('order_state', $order_state)->order('create_datetime DESC')->find();
        if (empty($orderFind)) {
            $order->promotion_uuid = $promotion_uuid;
            $order->fAgencyNo = $fccode;
            $order->order_state = $order_state;
            $order->save();
            $orderFind['order_uuid'] = $order->order_uuid;
            $orderFind['promotion_uuid'] = $order->promotion_uuid;
            $orderFind['fOrderNo'] = NULL;
            $orderFind['order_state'] = $order->order_state;
        }
        
        return $orderFind;
    }
    
    /**
     * 检查订单体积是否有超标
     * @param   string $order_uuid      订单唯一标识
     * @param   string $order_item_uuid 订单明细唯一标识
     * @param   int    $fOrdQty         商品数量
     * @param   string $fCuM3           商品体积
     * @param   string $promotion_uuid  活动唯一标识
     * @return  bool                    布尔值
     */
    private function check_volume($order_uuid, $order_item_uuid, $fOrdQty, $fCuM3, $promotion_uuid = ''){
        $bool = true;
        if (empty($promotion_uuid)) {
            $promotion_uuid = DAILY_PROMOTION_UUID;
        }
        $promotion = new \backend\model\Promotion;
        $promotionFind = $promotion::field('max_volume')->where('promotion_uuid', $promotion_uuid)->find();
        if (!empty($promotionFind)) {
            if (empty($promotionFind['max_volume'])) {
                $bool = false;
            } else {
                $volume = floatval($fCuM3);
                $max_volume = floatval($promotionFind['max_volume']);
                $where = new Where;
                if (!empty($order_item_uuid)) {
                    $where['order_item_uuid'] = ['<>', $order_item_uuid];
                }
                $where['order_uuid'] = $order_uuid;
                $orderItem = new \backend\model\OrderItem;
                $orderItemFind = $orderItem::field('SUM(fOrdQty*fCuM3) curr_volume')->where('order_uuid', $order_uuid)->find();
                $curr_volume = $orderItemFind['curr_volume'];
                if ((($fOrdQty * $volume) + $curr_volume) <= $max_volume) {
                    $bool = false;
                }
            }
        }
        
        return $bool;
    }
}